{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Watch a Soft-Actor-Critic Agent!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.Start the Environment for Trained Agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "device:  cuda:0\n",
      "state_size:  24 , action_size:  4 , action_high:  1.0\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import torch\n",
    "import gym\n",
    "import time\n",
    "from  collections  import deque\n",
    "\n",
    "from sac_agent import soft_actor_critic_agent\n",
    "\n",
    "env = gym.make('BipedalWalker-v2')\n",
    "\n",
    "# Set seeds\n",
    "seed = 0 ## 12345\n",
    "env.seed(seed)\n",
    "torch.manual_seed(seed)\n",
    "np.random.seed(seed)\n",
    "\n",
    "eval=True \n",
    "LEARNING_RATE=0.0001\n",
    "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
    "print('device: ', device)\n",
    "\n",
    "state_size = env.observation_space.shape[0]\n",
    "action_size=env.action_space.shape[0]\n",
    "action_high= float(env.action_space.high[0])\n",
    "print('state_size: ', state_size, ', action_size: ', action_size, ', action_high: ', action_high)\n",
    "    \n",
    "agent = soft_actor_critic_agent(env.observation_space.shape[0], env.action_space, \\\n",
    "        device=device, hidden_size=256, lr=LEARNING_RATE, gamma=0.99, tau=0.005, alpha=0.2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2. Prepare Load"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load(agent, actor, critic):\n",
    "    print('Load model from {} and {}'.format(actor, critic))\n",
    "    agent.policy.load_state_dict(torch.load(actor))\n",
    "    agent.critic.load_state_dict(torch.load(critic))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3. Prepare Player"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def play(env, agent, num_episodes):\n",
    "    \n",
    "    state = env.reset()\n",
    "    scores_deque = deque(maxlen=100)\n",
    "    scores = []\n",
    "    \n",
    "    for i_episode in range(num_episodes + 1):\n",
    "        \n",
    "        state = env.reset()\n",
    "        score = 0                    \n",
    "        time_start = time.time()\n",
    "        \n",
    "        while True:\n",
    "            \n",
    "            ## action = agent.select_action(np.array(state)) ## TD3\n",
    "            action = agent.select_action(state, eval=True)\n",
    "            env.render()\n",
    "            next_state, reward, done, _ = env.step(action)\n",
    "            score += reward \n",
    "            state = next_state\n",
    "    \n",
    "            if done:\n",
    "                break\n",
    "                \n",
    "        s = (int)(time.time() - time_start)\n",
    "        \n",
    "        scores_deque.append(score)\n",
    "        scores.append(score)    \n",
    "        \n",
    "        print('Episode {}\\tAverage Score: {:.2f},\\tScore: {:.2f} \\tTime: {:02}:{:02}:{:02}'\\\n",
    "                  .format(i_episode, np.mean(scores_deque), score, s//3600, s%3600//60, s%60)) \n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4. Load and Play,  lr = 0.0001, 756 episodes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Load model from dir_chk\\weights_actor_lr0001.pth and dir_chk\\weights_critic_lr0001.pth\n",
      "Episode 0\tAverage Score: 304.74,\tScore: 304.74 \tTime: 00:00:24\n",
      "Episode 1\tAverage Score: 304.72,\tScore: 304.69 \tTime: 00:00:16\n",
      "Episode 2\tAverage Score: 304.54,\tScore: 304.19 \tTime: 00:00:16\n",
      "Episode 3\tAverage Score: 304.63,\tScore: 304.88 \tTime: 00:00:17\n"
     ]
    }
   ],
   "source": [
    "actor = 'dir_chk\\weights_actor_lr0001.pth'    \n",
    "critic = 'dir_chk\\weights_critic_lr0001.pth'\n",
    "\n",
    "load(agent, actor, critic)\n",
    "play(env, agent, num_episodes=3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5. Load and Play,  lr = 0.0005, 540 episodes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Load model from dir_chk\\weights_actor_lr0005.pth and dir_chk\\weights_critic_lr0005.pth\n",
      "Episode 0\tAverage Score: 318.72,\tScore: 318.72 \tTime: 00:00:16\n",
      "Episode 1\tAverage Score: 318.53,\tScore: 318.35 \tTime: 00:00:16\n",
      "Episode 2\tAverage Score: 318.43,\tScore: 318.23 \tTime: 00:00:16\n",
      "Episode 3\tAverage Score: 318.55,\tScore: 318.90 \tTime: 00:00:16\n"
     ]
    }
   ],
   "source": [
    "actor = 'dir_chk\\weights_actor_lr0005.pth'    \n",
    "critic = 'dir_chk\\weights_critic_lr0005.pth'\n",
    "\n",
    "load(agent, actor, critic)\n",
    "play(env, agent, num_episodes=3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6. Load and Play,  lr = 0.00008,  408 episodes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Load model from dir_chk\\weights_actor_lr00008.pth and dir_chk\\weights_critic_lr00008.pth\n",
      "Episode 0\tAverage Score: 303.68,\tScore: 303.68 \tTime: 00:00:18\n",
      "Episode 1\tAverage Score: 305.97,\tScore: 308.26 \tTime: 00:00:18\n",
      "Episode 2\tAverage Score: 306.69,\tScore: 308.13 \tTime: 00:00:18\n"
     ]
    }
   ],
   "source": [
    "actor = 'dir_chk\\weights_actor_lr00008.pth'    \n",
    "critic = 'dir_chk\\weights_critic_lr00008.pth'\n",
    "\n",
    "load(agent, actor, critic)\n",
    "play(env, agent, num_episodes=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "env.close()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "kernel-ml",
   "language": "python",
   "name": "kernel-ml"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
